const app = getApp();
// 统一请求头
const BASE_URL = app.globalData.baseUrl;

/**
 * 获取token
 * @returns {{token}}
 */
const requestHeader = function () {
    let token = app.globalData.token;
    if (!token) {
        const tokenStorage = wx.getStorageSync('token').token
        if (tokenStorage) token = tokenStorage
    }
    return {
        'token': token
    }
};

/**
 * 统一请求模板
 * @param {*} url
 * @param {*} method
 * @param {Object} data 参数
 * @param {Object} header 请求头
 */
const request = (url, method, data, token) => {
    const _method = method.toLowerCase();
    return new Promise((resolve, reject) => {
        wx.request({
            url: BASE_URL + url,
            data,
            method: _method,
            header: !token ? requestHeader() : '',
            success(res) {
                const { data } = res;
                if (data.code === 200) {
                    console.log('[请求成功] => ' + url, data);
                    resolve(data)
                } else {
                    console.log('[请求成功] => ' + url, data);
                    if (data.code === 102 || data.code === 108) {
                        wx.showToast({
                            title: '登录中...',
                            icon: "none"
                        });
                        setTimeout(async () => {
                            wx.clearStorageSync('token');
                            await wxLogin();
                            wx.reLaunch({
                                url: '/pages/index/index',
                            })
                        }, 1000)
                    }
                    resolve(data)
                }
            },
            fail(err) {
                wx.showToast({
                    title: `网络繁忙, 请稍后再试!`,
                    icon: "none"
                });
                reject(err)
            }
        })
    })
};

// 用户登录
const wxLogin = () => {
    return new Promise((resolve, reject) => {
      wx.login({
        success: async (res) => {
          const r = await login(res.code);
          if (r.code == 200) {
            saveInfo(r.data)
            resolve({ code: 200 })
          } else if (r.code == 107) {
            resolve({ code: 107 })
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '登录失败, 请重试',
            icon: 'none'
          })
          reject({ code: 500 })
        }
      })
    })
};

// 用户注册
const wxRegister = () => {
    return new Promise((resolve,reject)=>{
      wx.getUserProfile({
        desc: '展示用户信息',
        success: (result) => {
          const { encryptedData, iv, rawData, signature } = result
          wx.login({
            timeout: 3000,
            success: (response) => {
              request('/user/register', 'post', {
                "code": `${response.code}`,
                "encryptedData": `${encryptedData}`,
                "iv": `${iv}`,
                "rawData": `${rawData}`,
                "signature": `${signature}`
              }).then(res=>{
                if(res.code == '104'){
                    wxLogin().then(res1 => {
                        if(res1.code == 200)
                            resolve(res1)
                        else 
                            reject(res1)
                    })
                }else if(res.code == 200){
                    saveInfo(res.data)
                    resolve({code:200})
                }else{
                  wx.showToast({
                    title: `注册失败, 请重新授权`,
                    icon: 'none'
                  })
                }
              })
            },
            fail: (res) => {
            },
            complete: (res) => { },
          })
        },
        fail: (res) => { 
          console.log("fail: ",res)
        },
        complete: (res) => { },
      })
    })
};

// 调用后端登录API
const login = (data) => {
    return request('/user/login/'+data, 'post', '')
};

// 保存用户信息
const saveInfo = (data) => {
    wx.setStorageSync("token",data.token)
    app.globalData.token = data.token
    wx.setStorageSync('userInfo', JSON.stringify(data))
}

module.exports = {
  request,
  wxLogin,
  wxRegister,
  BASE_URL,
  requestHeader
}